package api

import (
	"fmt"

	"gitee.com/hexug/devcloud/mcenter/apps"
	"gitee.com/hexug/devcloud/mcenter/apps/user"
	restfulspec "github.com/emicklei/go-restful-openapi/v2"
	"github.com/emicklei/go-restful/v3"
)

var _ apps.HttpObj = (*ApiServer)(nil)

type ApiServer struct {
	Svc user.Server
}

func (a *ApiServer) Name() string {
	return user.AppName
}

func (a *ApiServer) Init() error {
	a.Svc = apps.GetApp(user.AppName).(user.Server)
	if a.Svc == nil {
		return fmt.Errorf("app %s 获取失败,疑似尚未注册", user.AppName)
	}
	return nil
}
func (h *ApiServer) Version() string {
	return "v1"
}

// 注册路由
func (a *ApiServer) ReagisterRoute(ws *restful.WebService) {
	tags := []string{"用户"}
	//设置子路由
	// http://127.0.0.1:2345/mcenter/api/v1/users  post
	ws.Route(ws.POST("/").To(a.CreateUser).
		//设置路由的描述信息
		Doc("创建用户").
		//设置路由的所属组标签
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata("auth", false).
		Reads(user.CreateUserRequest{}).
		Writes(user.User{}).
		Returns(200, "OK", user.User{}))
	//http://127.0.0.1:2345/mcenter/api/v1/users  delete
	ws.Route(ws.DELETE("/").To(a.DeleteUser).
		//设置路由的描述信息
		Doc("删除用户").
		//设置路由的所属组标签
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata("auth", true).
		Reads(user.DeleteUserRequest{}).
		Writes(user.User{}).
		Returns(200, "OK", user.User{}))
	//http://127.0.0.1:2345/mcenter/api/v1/users  patch
	ws.Route(ws.PATCH("/").To(a.UpdateUser).
		//设置路由的描述信息
		Doc("更新用户").
		//设置路由的所属组标签
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata("auth", true).
		Reads(user.UpdateUserRequest{}).
		Writes(user.User{}).
		Returns(200, "OK", user.User{}))
	//http://127.0.0.1:2345/mcenter/api/v1/users/list get
	ws.Route(ws.GET("/list").To(a.QueryUser).
		//设置路由的描述信息
		Doc("查询用户列表").
		//设置路由的所属组标签
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata("auth", true).
		Reads(user.QueryUserRequest{}).
		Writes(user.UserSet{}).
		Returns(200, "OK", user.UserSet{}))
	//http://127.0.0.1:2345/mcenter/api/v1/users/{id} get
	ws.Route(ws.GET("/{id}").To(a.DetailUser).
		//设置路由的描述信息
		Doc("查询用户详情").
		//设置路由的所属组标签
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata("auth", true).
		Reads(user.DeleteUserRequest{}).
		Writes(user.User{}).
		Returns(200, "OK", user.User{}))
}

func init() {
	apps.RegisterHttp(&ApiServer{})
}
